package com.study.spring.security.service;

import com.study.spring.security.bean.PermissionExt;
import com.study.spring.security.bean.UserInfo;
import com.study.spring.security.mapper.PermissionMapper;
import com.study.spring.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class LuUserDetailsServiceImpl1 implements UserDetailsService, UserService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserInfo user = getByUsername(userName);
        if (user != null) {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            List<PermissionExt> permissions = permissionMapper.selectByUserId(user.getId());
            permissions.forEach(permission -> {
                if (permission != null &&
                        !StringUtils.isEmpty(permission.getEnname())) {
                    GrantedAuthority grantedAuthority = new
                            SimpleGrantedAuthority(permission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
            return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }

    @Override
    public UserInfo getByUsername(String username) {
        return userMapper.getUserByName(username);
    }
}
